import { Body, Controller, Get, Param, Patch, Post } from '@nestjs/common';
import { BaseController } from '@/controllers/base.controller';
import { halt, ok } from '@/utils';
import { AutosaleService } from '@/services/autosale.service';
import { AssetAutoSale } from '@prisma/client';
import {
  AssetAutoSaleCreateDto,
  AssetAutoSaleQueryDto,
  AssetAutoSaleUpdateDto,
} from '@/dtos/autosale.dto';
import { CurrentUser } from '@/decorators';

@Controller('autosale')
export class AutosaleController extends BaseController {
  constructor(private readonly AutosaleService: AutosaleService) {
    super();
  }

  @Get('admin/service/status')
  async status() {
    const queueCache = await this.redis.exists('bull:autosale:repeat');
    if (!queueCache) {
      return ok(0);
    } else {
      return ok(1);
    }
  }

  @Get('admin/service/switch')
  async witch() {
    const queueCache = await this.redis.exists('bull:autosale:repeat');
    if (!queueCache) {
      await this.AutosaleService.serviceStart();
      return ok(1);
    } else {
      await this.AutosaleService.serviceClose();
      return ok(0);
    }
  }

  // @Get('admin/cache/:assetId')
  // async cache(@Param('assetId') assetId: number) {
  //   // 查询自动交易详情
  //   const detail = await this.AutosaleService.detail(assetId);
  //
  //   let status;
  //   if (detail.status == false) {
  //     if (!detail.sellerId) {
  //       return halt('挂售账户异常');
  //     }
  //     const res = await this.AutosaleService.cache(assetId, detail.sellerId);
  //     if (!res) {
  //       return halt('缓存队列异常，检查是否持有藏品');
  //     }
  //     status = true;
  //   } else {
  //     const res = await this.AutosaleService.clean(assetId);
  //     if (!res) {
  //       return halt('清除队列异常');
  //     }
  //     status = false;
  //   }
  //
  //   return ok(
  //     await this.AutosaleService.update({
  //       where: {
  //         assetId,
  //       },
  //       data: {
  //         status: status,
  //       },
  //     }),
  //   );
  // }

  @Post('admin/query')
  async query(@Body() dto: AssetAutoSaleQueryDto) {
    return ok(await this.AutosaleService.query(dto));
  }

  @Post('admin/create')
  async create(
    @Body() dto: AssetAutoSaleCreateDto,
    @CurrentUser('id') id: number,
  ) {
    dto.data.operator = id;
    return ok(await this.AutosaleService.create(dto.data));
  }

  @Patch('admin/update')
  async update(@Body() dto: AssetAutoSaleUpdateDto) {
    return ok(await this.AutosaleService.update(dto));
  }

  @Post('admin/job/switch')
  async jobSwitch(@Body('id') id: number) {
    return ok(await this.AutosaleService.jobSwitch(id));
  }
}
